import { login,login2, getUserInfo,logout } from "@/api/login";
import { getToken, setToken, removeToken } from '@/utils/auth'

const user = {
    state: {
        token: getToken(),
        userData: "",
        permissions: []
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_ROLENAME: (state, userData) => {
            state.userData = userData;
        },
        SET_PERMISSIONS: (state, permissions) => {
            state.permissions = permissions
          }
    },
    actions: {
        //登录
        Login({ commit }, userInfo) {
            // const username = userInfo.username.trim();
            // const password = userInfo.password;
            return new Promise((resolve, reject) => {
                login(userInfo).then(res => {
                    setToken(res.token);
                    commit('SET_TOKEN', res.token);
                    resolve();
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //无验证码登录
        Login2({ commit }, userInfo) {
            // const username = userInfo.username.trim();
            // const password = userInfo.password;
            return new Promise((resolve, reject) => {
                login2(userInfo).then(res => {
                    setToken(res.token);
                    commit('SET_TOKEN', res.token);
                    resolve();
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getUserInfo().then(res => {
                    const userData = res.data.user;
                    commit("SET_ROLENAME", userData);
                    commit('SET_PERMISSIONS', res.data.permissions)
                    resolve(res);
                }).catch(error => {
                    reject(error);
                })
            })
        },
        // 退出系统
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user